package com.jiedeng.controller;

import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * @author 覃远龙
 * @ClassName: RecorderController
 * @Description:
 * @date 2017/8/14 13:55
 */
@RestController
@RequestMapping("/recorder")
public class RecorderController {

    @Autowired
    ITaskRepository taskRepository;

    @Autowired
    IEventRepository eventRepository;

    @Autowired
    ICheckRepository checkRepository;

    @Autowired
    IFileRecordRepository fileRecordRepository;

    @Autowired
    ICheckItemRepository checkItemRepository;

    @Autowired
    ICheckItemRuleRepository checkItemRuleRepository;

    @Autowired
    IPersonRepository personRepository;

    @Autowired
    INatRepository natRepository;

    @Autowired
    INormRepository normRepository;

    @Autowired
    IRankRepository rankRepository;

    @Autowired
    ICheckCountRepository checkCountRepository;

    @Autowired
    ICorpRepository corpRepository;

    @Autowired
    IProjectPersonRepository projectPersonRepository;
    @Autowired
    ISysConfigRepository sysConfigRepository;

    @RequestMapping(value = "/filterTask", method = RequestMethod.GET)
    @ApiOperation(value = "1、T_Task表")
    public List<Task> filterTask(final long taskPersonId, final String excutePersonId, final long closePersonId, final long pubPersonId, final long verifyPersonId, final boolean isDelete, final long projectId) {
        Specification<Task> sp = new Specification<Task>() {
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                Predicate isDeletePre = null;
                Predicate projectPre = null;
                if (taskPersonId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("taskPersonId"), taskPersonId);
                    predicates.add(p1);
                }
                if (closePersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("closePersonId"), closePersonId));
                }
                if (pubPersonId > 0) {
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("pubPersonId"), pubPersonId)));
                }
                if (verifyPersonId > 0) {
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("verifyPersonId"), verifyPersonId)));
                }

                if (excutePersonId != null && !excutePersonId.isEmpty()) {
                    ParameterExpression<String> p = criteriaBuilder.parameter(String.class, "excutePersonId");
                    predicates.add(criteriaBuilder.or(criteriaBuilder.like(root.<String>get("excutePersonId"), "%" + excutePersonId + ",%")));
                }

                // 只有like不能匹配单字符情况
                if (excutePersonId != null && !excutePersonId.isEmpty()) {
                    ParameterExpression<String> p = criteriaBuilder.parameter(String.class, "excutePersonId");
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.<String>get("excutePersonId"), excutePersonId)));
                }
                if (projectId > 0) {
                    projectPre = criteriaBuilder.and(criteriaBuilder.equal(root.get("projectId"), projectId));
//                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("projectId"), projectId)));
                }

                isDeletePre = criteriaBuilder.equal(root.get("isDelete"), isDelete);
                //排序
//                criteriaBuilder.and(isDeletePre, criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()])));
                criteriaQuery.where(criteriaBuilder.and(projectPre, isDeletePre, criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]))));
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("startTime")));
                return criteriaQuery.getRestriction();
//                return criteriaBuilder.and(projectPre, isDeletePre, criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()])));
            }
        };

        List<Task> tasks = taskRepository.findAll(sp);
        if (excutePersonId == null || excutePersonId.isEmpty()) {
            return tasks;
        }
        boolean isSign = Boolean.valueOf(sysConfigRepository.findByKey0("isSign ").get(0).getValue0());
        List<Task> taskFilter = new ArrayList<Task>();
        for (Task t : tasks) {
            String[] stringList = t.getExcutePersonId().split(",");
            for (String s : stringList) {
                if ((s.trim().equals(excutePersonId.trim()) && isSign && t.isVerify()) || (s.trim().equals(excutePersonId.trim()) && !isSign) || taskPersonId == t.getTaskPersonId() || closePersonId == t.getClosePersonId() || pubPersonId == t.getPubPersonId() || verifyPersonId == t.getVerifyPersonId()) {
                    taskFilter.add(t);
                    break;
                }
            }
        }
        return taskFilter;

    }

    /**
     * 根据key获取对应的配置对象
     *
     * @param kelid
     * @return
     */
    /*@RequestMapping(value = "/findSysConfigByKey", method = RequestMethod.GET)
    public SysConfig findSysConfigByKelid(String kelid) {
        List<SysConfig> sysConfigs = sysConfigRepository.findByKelid(kelid);
        if (sysConfigs != null && !sysConfigs.isEmpty()) {
            return sysConfigs.get(0);
        }
        return null;
    }*/

    /**
     * 获取sys_config表所有数据
     *
     * @return
     */
    @RequestMapping(value = "/findAllSysConfig", method = RequestMethod.GET)
    public List<SysConfig> findSysConfigByKelid() {
        List<SysConfig> sysConfigs = sysConfigRepository.findAll();
        return sysConfigs;
    }

    /**
     * 获取任务
     *
     * @param taskPersonId
     * @param excutePersonId
     * @param closePersonId
     * @param pubPersonId
     * @param verifyPersonId
     * @param isDelete
     * @return
     */
    @RequestMapping(value = "/filterTaskManage", method = RequestMethod.GET)
    @ApiOperation(value = "1、T_Task表")
    public List<Task> filterTaskManage(final long taskPersonId, final String excutePersonId, final long closePersonId, final long pubPersonId, final long verifyPersonId, final boolean isDelete) {//, int page,int pageSize

        Specification<Task> sp = new Specification<Task>() {
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                Predicate isDeletePre = null;
                if (taskPersonId > 0) {
                    Predicate p1 = criteriaBuilder.equal(root.get("taskPersonId"), taskPersonId);
                    predicates.add(p1);
                }
                if (closePersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("closePersonId"), closePersonId));
                }
                if (pubPersonId > 0) {
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("pubPersonId"), pubPersonId)));
                }
                if (verifyPersonId > 0) {
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("verifyPersonId"), verifyPersonId)));
                }
                if (excutePersonId != null && !excutePersonId.isEmpty()) {
                    //ParameterExpression<String> p = criteriaBuilder.parameter(String.class, "excutePersonId");
                    predicates.add(criteriaBuilder.or(criteriaBuilder.like(root.<String>get("excutePersonId"), "%" + excutePersonId + ",%")));
                }
                // 只有like不能匹配单字符情况
                if (excutePersonId != null && !excutePersonId.isEmpty()) {
                    //ParameterExpression<String> p = criteriaBuilder.parameter(String.class, "excutePersonId");
                    predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.<String>get("excutePersonId"), excutePersonId)));
                }

                isDeletePre = criteriaBuilder.equal(root.get("isDelete"), isDelete);
//                Predicate[] p = new Predicate[predicates.size()];
                criteriaQuery.where(criteriaBuilder.and(isDeletePre, criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]))));
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("startTime")));

                return criteriaQuery.getRestriction();

            }
        };

        //Pageable pageable=new PageRequest(page, pageSize);  //分页信息
        List<Task> tasks = taskRepository.findAll(sp);
        if (excutePersonId == null || excutePersonId.isEmpty()) {
            return tasks;
        }

        List<Task> taskFilter = new ArrayList<Task>();
        for (Task t : tasks) {
            String[] stringList = t.getExcutePersonId().split(",");
            for (String s : stringList) {
                if (s.trim().equals(excutePersonId.trim()) || taskPersonId == t.getTaskPersonId() || closePersonId == t.getClosePersonId() || pubPersonId == t.getPubPersonId() || verifyPersonId == t.getVerifyPersonId()) {
                    taskFilter.add(t);
                    break;
                }
            }
        }
        return taskFilter;

    }

    @RequestMapping(value = "filterEvent", method = RequestMethod.GET)
    @ApiOperation(value = "2、T_Event表")
    public List<Event> filterEvent(final String exePersonId, final long projectId) {
        Specification<Event> sp = new Specification<Event>() {
            @Override
            public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (exePersonId != null && !exePersonId.isEmpty()) {
                    predicates.add(criteriaBuilder.equal(root.get("excutePersonId"), exePersonId));
                }
                if (projectId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("projectId"), projectId));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        List<Event> events = eventRepository.findAll(sp, new Sort(Sort.Direction.DESC, "excuteTime"));
        for (Event e : events) {
            List<Check> checks = checkRepository.findByEventId(e.getId());
            e.setChecks(checks);
            if (checks != null) {
                e.setCheckCount(checks.size());
            }
        }
        return events;
    }

    @RequestMapping(value = "/filterEvent2", method = RequestMethod.GET)
    @ApiOperation(value = "2.1、查询值：Project_ID（当前项目）")
    public List<Map<String, Object>> filterEvent2(final String personId, final long projectId) {
        Specification<Event> sp = new Specification<Event>() {
            @Override
            public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicates = null;
                List<Predicate> predicateAnd = new ArrayList<Predicate>();
                Predicate predicateOr = null;
                boolean isDraft = false;
                if (projectId > 0) {
                    predicates = criteriaBuilder.equal(root.get("projectId"), projectId);
                }
                if (!personId.isEmpty()) {
                    predicateAnd.add(criteriaBuilder.equal(root.get("isDraft"), isDraft));
                    predicateAnd.add(criteriaBuilder.equal(root.get("eventPersonId"), personId));

                    predicateOr = criteriaBuilder.equal(root.get("excutePersonId"), personId);
                }
                return criteriaBuilder.and(predicates,
                        criteriaBuilder.or(predicateOr, criteriaBuilder.and(predicateAnd.toArray(new Predicate[predicateAnd.size()]))));
            }
        };

        List<Event> events = eventRepository.findAll(sp, new Sort(Sort.Direction.DESC, "excuteTime"));

        List<Map<String, Object>> filterEvent = new ArrayList<Map<String, Object>>();
        for (Event e : events) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("event", e);
            List<Check> checks = checkRepository.findByEventId(e.getId());
            map.put("checkCount", checks.size());
            filterEvent.add(map);
        }

        return filterEvent;
    }

    @RequestMapping(value = "/filterCheck", method = RequestMethod.GET)
    @ApiOperation(value = "3、\t查询：检查表(t_Check) ")
    public List<Check> searchCheckByTask(String task) {
        List<Check> checks = checkRepository.findByTaskId(task);
        return checks;
    }

    @RequestMapping(value = "/filterCheck2", method = RequestMethod.GET)
    @ApiOperation(value = "4、\t联合查询：检查表(t_Check)、文件记录表（t_FileRecord）")
    public List<Check> filterCheckAndFileRecord(String taskId, boolean isCloseFile) {
        List<Check> checks = checkRepository.findByTaskIdAndIsCloseFile(taskId, isCloseFile);
        for (Check check : checks) {
            List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
            check.setFileRecords(fileRecords);
        }

        return checks;
    }

    @RequestMapping(value = "/filterEventByPersonId", method = RequestMethod.GET)
    @ApiOperation(value = "5、\t联合查询：事件表(t_Event)、文件记录表（t_FileRecord）")
    public List<Event> findEventByPerson(long personId) {
        List<Event> events = eventRepository.findByEventPersonId(personId);
        for (Event event : events) {
            List<Check> checks = checkRepository.findByEventId(event.getId());
            for (Check check : checks) {
                List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
                check.setFileRecords(fileRecords);
            }
            event.setChecks(checks);
        }

        return events;
    }

    @RequestMapping(value = "/filterCheckAndCheckItem", method = RequestMethod.GET)
    @ApiOperation(value = "6、\t联合查询：检查表(t_Check)、检查库表(t_CheckItem)、文件记录表（t_FileRecord）")
    public List<Check> findCheckAndCheckItem(String taskId) {
        List<Check> checks = checkRepository.findByTaskId(taskId);
        for (Check check : checks) {
            if (check.getCheckItemId() > 0) {
                Optional<CheckItem> checkItem = checkItemRepository.findById(check.getCheckItemId());
                check.setCheckItem(checkItem.get());
            }
            List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
            check.setFileRecords(fileRecords);
        }

        return checks;
    }

    @RequestMapping(value = "/filterCheckAndCheckItemById", method = RequestMethod.GET)
    @ApiOperation(value = "7、\t联合查询：检查表(t_Check)、检查库表(t_CheckItem) 、文件记录表（t_FileRecord）")
    public List<Check> findCheckAndCheckItemById(String taskId, boolean isCloseFile, long personId) {
        List<Check> checks = checkRepository.findByTaskIdAndIsCloseFileOrderByCheckTimeDesc(taskId, isCloseFile);

        for (Check check : checks) {
            if (check.getCheckItemId() > 0) {
                Optional<CheckItem> checkItem = checkItemRepository.findById(check.getCheckItemId());
                if (checkItem.isPresent()) check.setCheckItem(checkItem.get());
            }
            List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
            check.setFileRecords(fileRecords);
        }

        List<Check> filterCheck = new ArrayList<Check>();
        for (Check check : checks) {
            if (isCloseFile) {
                if (check.getCheckPersonId() == personId || (check.getExamPersonId() == personId && check.isPub()) || (check.getClosePersonId() == personId && check.isPub())) {
                    filterCheck.add(check);
                }
            }

            if (!isCloseFile) {
                if (check.getCheckPersonId() == personId) {
                    filterCheck.add(check);
                }
                if (check.getExamPersonId() == personId && check.isPub()) {
                    boolean flag = false;
                    for (Check check1 : filterCheck) {
                        if (check1.getId().equals(check.getId())) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        filterCheck.add(check);
                    }
                }
            }
        }


        return filterCheck;
    }

    @RequestMapping(value = "/filterCheckAndCheckItemByEvent", method = RequestMethod.GET)
    @ApiOperation(value = "0402 问题/亮点（下行）")
    public List<Check> findCheckAndCheckItemByEvent(String eventId, boolean isCloseFile) {
        List<Check> checks = checkRepository.findByEventIdAndIsCloseFileOrderByCheckTimeDesc(eventId, isCloseFile);

        for (Check check : checks) {
            if (check.getCheckItemId() > 0) {
                CheckItem checkItem = checkItemRepository.findById(check.getCheckItemId()).get();
                check.setCheckItem(checkItem);
            }
            List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
            check.setFileRecords(fileRecords);
        }

        return checks;
    }

    @RequestMapping(value = "/filterCheckAndCheckItemAndCheckRuleById", method = RequestMethod.GET)
    @ApiOperation(value = "8、\t联合查询：检查表(t_Check)、检查库表(t_CheckItem)和检查库权重规则表(t_CheckItemRule)")
    public Check findCheckAndCheckItemAndCheckRuleById(String checkId) {
        Check check = checkRepository.getOne(checkId);

        CheckItem checkItem = checkItemRepository.getOne(check.getCheckItemId());
        check.setCheckItem(checkItem);
        if (checkItem != null) {
            List<CheckItemRule> checkItemRules = checkItemRuleRepository.findByCheckItemId(checkItem.getId());
            checkItem.setCheckItemRules(checkItemRules);
        }

        List<FileRecord> fileRecords = fileRecordRepository.findByCheckId(check.getId());
        check.setFileRecords(fileRecords);

        return check;
    }

    @RequestMapping(value = "/newCheckRecord", method = RequestMethod.POST)
    @ApiOperation(value = "0403 问题（数据上行）")
    public Rst newCheckRecord(@RequestBody Check check) {
        checkRepository.save(check);
        if (check.getCheckItem() != null) {
            checkItemRepository.save(check.getCheckItem());
        }
        if (check.getFileRecords() != null && check.getFileRecords().size() > 0) {
            for (FileRecord fileRecord : check.getFileRecords()) {
                fileRecordRepository.save(fileRecord);
            }
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");

        return rst;
    }

    @RequestMapping(value = "/newCheckRecordBatch", method = RequestMethod.POST)
    @ApiOperation(value = "0403 问题（数据上行）批量")
    public Rst newCheckRecordBatch(@RequestBody List<Check> checks) {
        for (Check check : checks) {
            checkRepository.save(check);
            if (check.getCheckItem() != null) {
                checkItemRepository.save(check.getCheckItem());
            }
            if (check.getFileRecords() != null && check.getFileRecords().size() > 0) {
                for (FileRecord fileRecord : check.getFileRecords()) {
                    fileRecordRepository.save(fileRecord);
                }
            }
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");

        return rst;
    }

    @RequestMapping(value = "/checkItemDetail", method = RequestMethod.GET)
    @ApiOperation(value = "0405 检查项详情页")
    public Map<String, Object> checkItemDetail(String checkId) {
        Check check = checkRepository.findById(checkId).get();
        Map<String, Object> map = new HashMap<String, Object>();
        CheckItem checkItem = checkItemRepository.getOne(check.getCheckItemId());

        if (checkItem.getNatId() > 0) {
            map.put("checkType", natRepository.getOne(checkItem.getNatId()).getCaption());
        } else {
            map.put("checkType", "");
        }
        map.put("Content", checkItem.getCaption());
        if (checkItem != null) {
            map.put("checkGist", checkItem.getChekItemDemand());
        } else {
            map.put("checkGist", "");
        }
        map.put("checkStand", checkItem.getChekItemDemand());
        if (checkItem != null) {
            //Rank rank = rankRepository.getOne(checkItem.getRankId());
            map.put("degree", checkItem.getCheckRequire());
        } else {
            map.put("degree", "");
        }
        map.put("demand", checkItem.getMeasure());
        map.put("Comment", checkItem.getMemo());
        map.put("imageNum", checkItem.getCollectNum());
        map.put("reformAdvice", check.getExpressionDesc());
        map.put("modelPic", checkItem.getPicture());
        List<FileRecord> checkFileRecord = fileRecordRepository.findByCheckIdAndCheckCloseOrderByNumAsc(checkId, true);
        map.put("checkFileRecord", checkFileRecord);
        List<FileRecord> reformFileRecord = fileRecordRepository.findByCheckIdAndCheckCloseOrderByNumAsc(checkId, false);
        if (reformFileRecord != null && reformFileRecord.size() > 0) {
            long rT = reformFileRecord.get(0).getrTime().getTime();
            for (FileRecord fileRecord : reformFileRecord) {
                long temp = fileRecord.getrTime().getTime();
                if (temp > rT) {
                    rT = temp;
                }
            }
            map.put("finishTime", rT);
        } else {
            map.put("finishTime", "");
        }
        map.put("reformFileRecord", reformFileRecord);
        //Task task = taskRepository.getOne(check.getTaskId());
        if (check.getTaskId() != null && !check.getTaskId().isEmpty()) {
            Task task = taskRepository.findById(check.getTaskId()).get();
            if (task.getCloseCorpId() > 0) {
                Corp corp = corpRepository.findById(task.getCloseCorpId()).get();
                map.put("reformDutyDep", corp.getCaption());
            } else {
                map.put("reformDutyDep", "");
            }
            if (task.getClosePersonId() > 0) {
                Person p = personRepository.findById(task.getClosePersonId()).get();
                map.put("reformDutyPerson", p.getName());
            } else {
                map.put("reformDutyPerson", "");
            }
        } else {
            map.put("reformDutyDep", "");
            map.put("reformDutyPerson", "");
        }

        if (check.getCloseCorpId() > 0) {
            Corp cp = corpRepository.findById(check.getCloseCorpId()).get();
            map.put("reformDep", cp.getCaption());
        } else {
            map.put("reformDep", "");
        }

        if (check.getClosePersonId() > 0) {
            Person pReform = personRepository.findById(check.getClosePersonId()).get();
            map.put("reformPerson", pReform.getName());
        } else {
            map.put("reformPerson", "");
        }

        Person ap;
        if (check.getVerifyPersonId() > 0) {
            ap = personRepository.findById(check.getVerifyPersonId()).get();
            map.put("auditPerson", ap.getName());
        } else {
            map.put("auditPerson", "");
        }

        return map;

    }

    @RequestMapping(value = "/checkDetail", method = RequestMethod.GET)
    @ApiOperation(value = "0405 检查项详情页")
    public Map<String, Object> checkDetail(String checkId) {
        Check check = checkRepository.findById(checkId).get();
        Map<String, Object> map = new HashMap<String, Object>();
        CheckItem checkItem = checkItemRepository.getOne(check.getCheckItemId());

        if (checkItem.getNatId() > 0) {
            map.put("checkType", natRepository.getOne(checkItem.getNatId()).getCaption());
        } else {
            map.put("checkType", "");
        }
        map.put("Content", checkItem.getCaption());
        if (checkItem != null) {
            map.put("checkGist", checkItem.getChekItemDemand());
        } else {
            map.put("checkGist", "");
        }
        map.put("checkStand", checkItem.getChekItemDemand());
        if (checkItem != null) {
            //Rank rank = rankRepository.getOne(checkItem.getRankId());
            map.put("degree", checkItem.getCheckRequire());
        } else {
            map.put("degree", "");
        }
        map.put("demand", checkItem.getMeasure());
        map.put("Comment", checkItem.getMemo());
        map.put("imageNum", checkItem.getCollectNum());
        map.put("reformAdvice", check.getExpressionDesc());
        map.put("closeMemo", check.getCloseMemo());
        map.put("modelPic", checkItem.getPicture());
        List<FileRecord> checkFileRecord = fileRecordRepository.findByCheckIdAndCheckCloseOrderByNumAsc(checkId, true);
        //占位
        List<FileRecord> checkFileList = new ArrayList<>();
        checkFileList.add(new FileRecord("seizeASeat01", 1));
        checkFileList.add(new FileRecord("seizeASeat02", 2));
        checkFileList.add(new FileRecord("seizeASeat03", 3));
        if (checkFileRecord != null) {
            for (FileRecord fileRecord : checkFileRecord) {
                if (fileRecord.getNum() < 4)
                    checkFileList.set(fileRecord.getNum() - 1, fileRecord);
            }
        }
        map.put("checkFileRecord", checkFileList);
//        map.put("checkFileRecord", checkFileRecord);
        List<FileRecord> reformFileRecord = fileRecordRepository.findByCheckIdAndCheckCloseOrderByNumAsc(checkId, false);
        //占位
        List<FileRecord> reformFileRecordList = new ArrayList<>();
        reformFileRecordList.add(new FileRecord("seizeASeatRe01", 1));
        reformFileRecordList.add(new FileRecord("seizeASeatRe02", 2));
        reformFileRecordList.add(new FileRecord("seizeASeatRe03", 3));
        if (reformFileRecord != null && reformFileRecord.size() > 0) {
            long rT = reformFileRecord.get(0).getrTime().getTime();
            for (FileRecord fileRecord : reformFileRecord) {
                if (fileRecord.getNum() < 4)
                    reformFileRecordList.set(fileRecord.getNum() - 1, fileRecord);
                long temp = fileRecord.getrTime().getTime();
                if (temp > rT) {
                    rT = temp;
                }
            }
            map.put("finishTime", rT);
        } else {
            map.put("finishTime", "");
        }
        map.put("reformFileRecord", reformFileRecord);
        //Task task = taskRepository.getOne(check.getTaskId());
        if (check.getTaskId() != null && !check.getTaskId().isEmpty()) {
            Task task = taskRepository.findById(check.getTaskId()).get();
            if (task.getCloseCorpId() > 0) {
                Corp corp = corpRepository.findById(task.getCloseCorpId()).get();
                map.put("reformDutyDep", corp.getCaption());
            } else {
                map.put("reformDutyDep", "");
            }
            if (task.getClosePersonId() > 0) {
                Person p = personRepository.findById(task.getClosePersonId()).get();
                map.put("reformDutyPerson", p.getName());
            } else {
                map.put("reformDutyPerson", "");
            }
        } else {
            map.put("reformDutyDep", "");
            map.put("reformDutyPerson", "");
        }

        if (check.getCloseCorpId() > 0) {
            Corp cp = corpRepository.findById(check.getCloseCorpId()).get();
            map.put("reformDep", cp.getCaption());
        } else {
            map.put("reformDep", "");
        }

        if (check.getClosePersonId() > 0) {
            Person pReform = personRepository.findById(check.getClosePersonId()).get();
            map.put("reformPerson", pReform.getName());
        } else {
            map.put("reformPerson", "");
        }

        Person ap;
        if (check.getVerifyPersonId() > 0) {
            ap = personRepository.findById(check.getVerifyPersonId()).get();
            map.put("auditPerson", ap.getName());
        } else {
            map.put("auditPerson", "");
        }

        return map;

    }

    @RequestMapping(value = "/getCheckItemByPropId", method = RequestMethod.GET)
    @ApiOperation(value = "0501 库表")
    public List<CheckItem> getCheckItemByprop(int propId) {
        List<CheckItem> checkItems = checkItemRepository.findByPropId(propId);
        for (CheckItem checkItem : checkItems) {
            List<CheckItemRule> checkItemRules = checkItemRuleRepository.findByCheckItemId(checkItem.getId());
            checkItem.setCheckItemRules(checkItemRules);
        }
        return checkItems;
    }

    @RequestMapping(value = "/saveCheckCount", method = RequestMethod.POST)
    @ApiOperation(value = "0601 打分表【数据上行】")
    public Rst saveCheckCount(@RequestBody List<CheckCount> checkCounts) {
        for (CheckCount checkCount : checkCounts) {
            checkCountRepository.save(checkCount);
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/getCheckCounts", method = RequestMethod.GET)
    @ApiOperation(value = "0602 【数据下行】")
    public List<CheckCount> getCheckCounts(String checkId) {
        List<CheckCount> checkCounts = checkCountRepository.findByCheckId(checkId);
        return checkCounts;
    }

    @RequestMapping(value = "/deleteCheck", method = RequestMethod.POST)
    @ApiOperation(value = "删除指定的check表数据")
    public Rst deleteCheck(String checkId) {
        checkRepository.deleteById(checkId);

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/updateFileRecord", method = RequestMethod.POST)
    @ApiOperation(value = "更新FileRecord表")
    public Rst updateFileRecord(@RequestBody FileRecord fileRecord) {
        fileRecordRepository.save(fileRecord);

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/updateCheckTaskID", method = RequestMethod.POST)
    @ApiOperation(value = "九）事件合并")
    public Rst updateCheckTaskID(String events, String taskId, long examPersonId, long closePersonId, long closeCorpId) {
        String[] eventArr = events.split(",");
        for (String event : eventArr) {
            List<Check> checks = checkRepository.findByEventId(event);
            for (Check check : checks) {
                check.setTaskId(taskId);
                check.setExamPersonId(examPersonId);
                check.setClosePersonId(closePersonId);
                check.setCloseCorpId(closeCorpId);
                checkRepository.save(check);
            }

        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/updateProjectPerson", method = RequestMethod.POST)
    @ApiOperation(value = "01001） 插入t_project_person表数据（数据上行）")
    public Rst updateProjectPerson(@RequestBody ProjectPerson projectPerson) {
        Rst rst = new Rst();
        List<ProjectPerson> pp = projectPersonRepository.findByPersonIdAndProjectIdAndPostId(projectPerson.getPersonId(), projectPerson.getProjectId(), projectPerson.getPostId());
        if (pp == null || pp.size() == 0) {
            ProjectPerson ppSave = projectPersonRepository.save(projectPerson);
            rst.setResultCode(0);
            rst.setMsg("OK");
            rst.setResult(ppSave);
        } else {
            rst.setResultCode(0);
            rst.setMsg("数据已存在");
        }


        return rst;
    }

    @RequestMapping(value = "/updateProjectPersons", method = RequestMethod.POST)
    @ApiOperation(value = "01002） 插入t_project_person表数据（数据上行）")
    public Rst updateProjectPersons(@RequestBody List<ProjectPerson> projectPersons) {
        List<ProjectPerson> persons = new ArrayList<ProjectPerson>();
        for (ProjectPerson projectPerson : projectPersons) {
            Rst rst = new Rst();
            List<ProjectPerson> pp = projectPersonRepository.findByPersonIdAndProjectIdAndPostId(projectPerson.getPersonId(), projectPerson.getProjectId(), projectPerson.getPostId());
            if (pp == null || pp.size() == 0) {
                ProjectPerson ppSave = projectPersonRepository.save(projectPerson);
                persons.add(ppSave);
            }
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        rst.setResult(persons);
        return rst;
    }

    @RequestMapping(value = "/updateEvents", method = RequestMethod.POST)
    @ApiOperation(value = "0303 事件（数据上行）")
    public Rst updateEventBatch(@RequestBody List<Event> events) {
        List<Event> le = new ArrayList<Event>();
        for (Event event : events) {
            Event e = eventRepository.save(event);
            le.add(e);
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        rst.setResult(le);
        return rst;
    }

    @RequestMapping(value = "/deleteeEvent", method = RequestMethod.POST)
    @ApiOperation(value = "0304 )删除一条事件")
    @Transactional
    public Rst deleteEvent(String eventId) {
        List<Check> checks = checkRepository.findByEventId(eventId);
        for (Check check : checks) {
            List<FileRecord> records = fileRecordRepository.findByCheckId(check.getId());
            for (FileRecord record : records) {
                fileRecordRepository.deleteById(record.getId());
            }
            List<CheckCount> checkCounts = checkCountRepository.findByCheckId(check.getId());
            for (CheckCount checkCount : checkCounts) {
                checkCountRepository.deleteById(checkCount.getId());
            }
            checkRepository.deleteById(check.getId());
        }
        eventRepository.deleteById(eventId);

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/deleteCheckCount", method = RequestMethod.POST)
    @ApiOperation(value = "0603 【数据删除】")
    public Rst deleteCheckCountByCheckId(String checkId) {
        List<CheckCount> checkCounts = checkCountRepository.findByCheckId(checkId);
        for (CheckCount checkCount : checkCounts) {
            checkCountRepository.deleteById(checkCount.getId());
        }

        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

    @RequestMapping(value = "/findCheckById", method = RequestMethod.GET)
    @ApiOperation(value = "查询一条check记录")
    public Check findCheckById(String checkId) {
        Check check = checkRepository.findById(checkId).get();
        List<FileRecord> records = fileRecordRepository.findByCheckId(checkId);
        check.setFileRecords(records);

        return check;
    }

    @RequestMapping(value = "/deleteCheckById", method = RequestMethod.POST)
    @ApiOperation(value = "查询一条check记录")
    public Rst deleteCheckById(String checkId) {
        checkRepository.deleteById(checkId);
        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("OK");
        return rst;
    }

}
